package chagine.core.http.filter;

import chagine.core.Env;
import chagine.core.current.CurrentEnv;
import chagine.core.current.CurrentRequestID;
import chagine.core.current.CurrentTenant;
import chagine.core.current.CurrentUser;
import cn.hutool.core.util.RandomUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * com.seeing.core.rpc.filter.WebRequestFilter
 * Created by 王彬安 on 2019/5/11.
 */
@Slf4j
@WebFilter(filterName = "CurrentRequestInfoFilter", urlPatterns = "/**")
public class WebRequestFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        log.info("=======WebRequestFilter===============doFilter================");
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        String userStr = httpServletRequest.getHeader(Env.HEAD_USERID_KEY);
        Long userId = null;
        try {
            if (!StringUtils.isEmpty(userStr)) {
                userId = Long.valueOf(userStr);
            }
        } catch (Exception ex) {
            log.warn("Request User Id {} is not Long.", userStr);
        }

        String tenantStr = httpServletRequest.getHeader(Env.HEAD_TENANT_KEY);
        Long tenantId = null;
        try {
            if (!StringUtils.isEmpty(tenantStr)) {
                tenantId = Long.valueOf(tenantStr);
            }
        } catch (Exception ex) {
            log.warn("Request tenant id {} is not Long.", tenantStr);
        }

        String requestIdStr = httpServletRequest.getHeader(Env.HEAD_REQUEST_ID_KEY);
        Long requestId = null;
        try {
            if (!StringUtils.isEmpty(requestIdStr)) {
                requestId = Long.valueOf(requestIdStr);
            }
        } catch (Exception ex) {
            log.warn("Request id {} is not Long.", requestIdStr);
        }
        if (requestId == null) {
            requestId = RandomUtil.randomLong(10_0000_0000_0000_0000L, 99_9999_9999_9999_9999L);
        }

        String requestTimeStr = httpServletRequest.getHeader(Env.HEAD_REQUEST_TIME_KEY);
        Long requestTime = null;
        try {
            if (!StringUtils.isEmpty(requestTimeStr)) {
                requestTime = Long.parseLong(requestTimeStr);
            }
        } catch (Exception ex) {
            log.warn("Request time {} is not Long.", requestIdStr);
        }
        if (requestTime == null) {
            requestTime = System.currentTimeMillis();
        }


        CurrentUser.setCurrentUser(userId);
        CurrentTenant.setCurrentTenant(tenantId);
        CurrentRequestID.setCurrentRequestID(requestId);
        CurrentEnv.setRequestTime(requestTime);

        String groupStr = httpServletRequest.getHeader(Env.HEAD_GROUPID_KEY);
        try {
            if (!StringUtils.isEmpty(groupStr)) {
                Long groupId = Long.parseLong(groupStr);
                CurrentEnv.setGroupId(groupId);
            }
        } catch (Exception ex) {
            log.warn("Request time {} is not Long.", requestIdStr);
        }

        String patientStr = httpServletRequest.getHeader(Env.HEAD_PATIENTID_KEY);
        try {
            if (!StringUtils.isEmpty(patientStr)) {
                Long patientId = Long.parseLong(patientStr);
                CurrentEnv.setPatientId(patientId);
            }
        } catch (Exception ex) {
            log.warn("Request time {} is not Long.", requestIdStr);
        }

        String employeeNo = httpServletRequest.getHeader(Env.HEAD_EMPLOYEE_NO_KEY);
        if (!StringUtils.isEmpty(employeeNo)) {
            CurrentEnv.setEmployeeNo(employeeNo);
        }else{
            log.warn("请求头 employeeno 为空");
        }



        String requestURI = httpServletRequest.getRequestURI();
        log.info("Http Request {} {} {} start.", httpServletRequest.getMethod(), requestURI, httpServletRequest.getQueryString());

        httpResponse.addHeader(Env.HEAD_REQUEST_ID_KEY, Long.toString(requestId));

        try {
            chain.doFilter(httpServletRequest, response);
        } finally {
            log.info("Http Request {} {} end.", httpServletRequest.getMethod(), requestURI);
            // 处理返回
            CurrentUser.setCurrentUser(null);
            CurrentTenant.setCurrentTenant(null);
            CurrentRequestID.setCurrentRequestID(null);
            CurrentEnv.setRequestTime(null);
            CurrentEnv.setMainTenaId(null);
            CurrentEnv.setGroupId(null);
            CurrentEnv.setGroupId(null);

        }
    }

    @Override
    public void destroy() {
    }
}
